import { getLocale } from 'locales';
import { useRecoilState, useRecoilValue } from 'recoil';

import ExpandLessIcon from '@mui/icons-material/ExpandLess';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { Box, Theme, useMediaQuery } from '@mui/material';
import CircularProgress from '@mui/material/CircularProgress';

import WhiteButton from 'components/atoms/buttons/whiteButton';

import { INestedMessage } from 'state/chat';
import { localeState } from 'state/project';
import { settingsState } from 'state/settings';

interface Props {
  message: INestedMessage;
  opened: boolean;
  loading?: boolean;
  onClick: () => void;
}

export default function DetailsButton({
  message,
  opened,
  onClick,
  loading
}: Props) {
  const { hideCot } = useRecoilValue(settingsState);
  const [locale] = useRecoilState(localeState);
  const nestedCount = message.subMessages?.length;
  const nested = !!nestedCount;
  const isMobile = useMediaQuery((theme: Theme) =>
    theme.breakpoints.down('sm')
  );

  const tool = nested
    ? message.subMessages![nestedCount - 1].author
    : undefined;

  const isRunningEmptyStep = loading && !message.content;
  const isRunningUserMessage = loading && message.authorIsUser;

  const show = nested || isRunningEmptyStep || isRunningUserMessage;

  if (!show || hideCot) {
    return null;
  }

  // Don't count empty steps
  const stepCount = nestedCount
    ? message.subMessages!.filter((m) => !!m.content).length
    : 0;

  const stepText =
    locale === 'en'
      ? `Took ${stepCount} step${stepCount <= 1 ? '' : 's'}`
      : `分 ${stepCount} 个步骤`;

  const text = loading
    ? tool
      ? `${getLocale('Using', locale)} ${tool}`
      : getLocale('Running', locale)
    : stepText;

  let id = '';
  if (tool) {
    id = tool.trim().toLowerCase().replaceAll(' ', '-');
  }
  if (loading) {
    id += '-loading';
  } else {
    id += '-done';
  }

  return (
    <WhiteButton
      id={id}
      disableElevation
      disableRipple
      sx={{
        textTransform: 'none'
      }}
      color="primary"
      startIcon={
        loading ? <CircularProgress color="inherit" size={16} /> : undefined
      }
      variant="contained"
      endIcon={
        nested && tool ? (
          opened ? (
            <ExpandLessIcon />
          ) : (
            <ExpandMoreIcon />
          )
        ) : undefined
      }
      onClick={tool ? onClick : undefined}
    >
      <Box
        sx={{
          maxWidth: isMobile ? 200 : 300,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis'
        }}
      >
        {text}
      </Box>
    </WhiteButton>
  );
}
